#include "worker.h"

int checkUserToken(int netfd, userInfo_t *userInfo, threadPool_t *pthreadPool)
{
    char sql[256] = {0};
    sprintf(sql, "SELECT name,rootId FROM userInformation WHERE cryptText='%s'", userInfo->password);
    puts(sql);
    m_MysqlQuery(pthreadPool->mysql, sql);
    MYSQL_RES *results = mysql_store_result(pthreadPool->mysql);
    if (results->row_count == 0) // 账户不存在
    {
        int si = -1;
        sendInfo(netfd, &si, sizeof(si));
        mysql_free_result(results);
        return -1;
    }
    else
    {
        int si = si_success;
        sendInfo(netfd, &si, sizeof(si));
        MYSQL_ROW row;
        row = mysql_fetch_row(results);
        // printf("row:%s %s\n", row[0], row[1]);
        strcpy(userInfo->username, row[0]);
        strcpy(userInfo->rootId, row[1]);
        if (userInfo->pos == -1)
        { // 如果没有位置信息则赋值为根目录
            userInfo->pos = atoi(row[1]);
            printf("row[1] %s,userInfo->pos:%d\n", row[1], userInfo->pos);
        }
        mysql_free_result(results);
        puts(userInfo->username);
        puts(userInfo->rootId);
        printf("userInfo password:%s,pos:%d\n", userInfo->password, userInfo->pos);
        return 0;
    }
}


int assignJobs(int netfd, threadPool_t *pthreadPool)
{
    userInfo_t userInfo;
    bzero(&userInfo, sizeof(userInfo));
    recvInfo(netfd, &userInfo);
    printf("userInfo password:%s,rootId:%s,pos:%d\n", userInfo.password, userInfo.rootId, userInfo.pos);
    checkUserToken(netfd, &userInfo, pthreadPool);
    int jobType = -1;
    recvInfo(netfd, &jobType);
    printf("jobType:%d\n", jobType);
    switch (jobType)
    {
    case signup:
        puts("signup");
        signUp(netfd, &userInfo, pthreadPool);
        break;
    case login:
        puts("login");
        checkID(netfd, &userInfo, pthreadPool);
        break;
    case print:

        break;
    case cli_cd:
        puts("cli_cd");
        m_cd(netfd, &userInfo, pthreadPool);
        break;
    case cli_ls:
        puts("cli_ls");
        m_ls(netfd, &userInfo, pthreadPool);
        break;
    case cli_pushs:
        puts("client push");
        saveFile(netfd, &userInfo, pthreadPool);
        break;
    case cli_polls:
        puts("client poll");
        downloadFile(netfd, &userInfo, pthreadPool);
        break;
    case cli_remove:

        break;
    case cli_pwd:
        m_pwd(netfd, &userInfo, pthreadPool);
        break;
    case cli_mkdir:
        puts("m_mkdir");
        m_mkdir(netfd, &userInfo, pthreadPool);
        break;
    default:
    {
    }
    break;
    }
}